package com.epalmpay.service.jobservice.impl;

import com.epalmpay.exception.ApplicationException;
import com.epalmpay.status.Rescode;
import com.epalmpay.entity.*;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.enumdef.CommonEnum.RunStatus;
import com.epalmpay.enumdef.CommonEnum.TaskType;
import com.epalmpay.mapper.*;
import com.epalmpay.service.activity.*;
import com.epalmpay.service.bonus.IBonusService;
import com.epalmpay.service.groupaccount.IGroupAccountService;
import com.epalmpay.service.jobservice.IActivityTaskService;
import com.epalmpay.util.Const;
import com.epalmpay.util.DateUtil;
import com.epalmpay.util.Logger;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wzq on 2017/6/2.
 */
@Service("activityTaskService")
public class ActivityTaskServiceImpl implements IActivityTaskService {

	protected Logger logger = Logger.getLogger(this.getClass());

	@Resource
	private RedpackageMapper redpackageMapper;
	@Resource
	private RedpackageUserMapper redpackageUserMapper;
	@Resource
	private CouponMapper couponMapper;
	@Resource
	private CouponUserMapper couponUserMapper;
	@Resource
	private GroupAccountMapper groupAccountMapper;
	@Resource
	GroupAccountLogMapper groupAccountLogMapper;
	@Resource
	ActivityBaseMapper activityBaseMapper;
	@Resource
    ActivityRoutineMapper activityRoutineMapper;
	@Resource
	MemberMapper memberMapper;
	@Resource
	ActivityRoutineRuleMapper activityRoutineRuleMapper;
	@Resource
	IRedPackageUserService redPackageUserService;
	@Resource
	ICouponUserService couponUserService;
	@Resource
	IBonusService bonusService;
	@Resource
	ActivityRoutineRegisterMapper activityRoutineRegisterMapper;
	@Resource
	private IActivityCouponService activityCouponService;
	@Resource
	private IActivityRedPackageService activityRedPackageService;
	@Resource
	StatisMemberMonthMapper statisMemberMonthMapper;
    @Resource
    private SysTaskLogMapper sysTaskLogMapper;
	@Resource
	private ActivityUnroutineMapper activityUnroutineMapper;
	@Resource
	private IGroupAccountService groupAccountService;
	@Resource
	private MallGoodMapper mallGoodMapper;
    @Resource
	private IActivityUnroutineService activityUnroutineService;

	@Resource(name="transactionManager")
	private DataSourceTransactionManager transactionManager;


	public int saveActivityDayTask(Date statisDate) throws Exception{
		int result=0;
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("taskType", TaskType.ActivityDayTask.getType());
		param.put("taskDate", statisDate);

		SysTaskLog oldRecord = sysTaskLogMapper.selectSysTaskLogByTypeAndDate(param);
		if(oldRecord  != null && oldRecord.getResultStatus() == RunStatus.Success.getType()){
			throw new ApplicationException(Rescode.FAIL,"计划任务已经执行成功！");
		}
		StringBuffer sb = new StringBuffer();

		//已建红包与优惠券自动过期
		autoExpireForCreatedRedPackageOrCoupon();
		//已发红包与优惠券自动过期
		autoExpireForSendedRedPackageOrCoupon();

		//动态活动到期自动结束
		autoExpireForUnroutineActivity();

		//服务商品过期自动下架
		autoOfflineExpireServiceGood();

		// 自动增加余额
		saveAutoAddAmount();

		//生日送
		saveActivityRoutineBirthDayTask(statisDate);
		//固定时间送
		saveActivityRoutineFixedTimeTask(statisDate);
		//会员生命周期赠送
		saveActivityMemberLifeCycleSendTask(statisDate);
		//插入计划任务成功日志
		if(oldRecord  == null){
			SysTaskLog record = new SysTaskLog();
			record.setGmtCreate(new Date());
			record.setGmtModified(new Date());
			record.setTaskType(TaskType.ActivityDayTask.getType());
			record.setTaskDate(statisDate);
			record.setResultStatus(RunStatus.Success.getType());
			record.setRunTimes(0);
			record.setMemo(sb.toString());
			result = sysTaskLogMapper.insert(record);
		}
		else{
			oldRecord.setGmtModified(new Date());
			oldRecord.setResultStatus(RunStatus.Success.getType());
			oldRecord.setRunTimes((oldRecord.getRunTimes()==null?0:oldRecord.getRunTimes())+1);
			oldRecord.setMemo(sb.toString());
			result = sysTaskLogMapper.updateByPrimaryKeySelective(oldRecord);
		}

		return result;
	}

	//已建红包与优惠券自动过期
	private int autoExpireForCreatedRedPackageOrCoupon()throws Exception{
		int result =0;

		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务
		TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态

		try {
			//优惠券自动过期
			activityCouponService.endExpireAllCoupon();
			//红包自动过期
			activityRedPackageService.endExpireAllRedpackage();
			transactionManager.commit(status);
		} catch (Exception e) {
			transactionManager.rollback(status);
			logger.error("已建红包与优惠券自动过期commit", e);
			throw e;
		}

		return result;
	}


	//已发红包与优惠券自动过期
	private int autoExpireForSendedRedPackageOrCoupon()throws Exception{
		int result =0;

		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务
		TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态

		try {
			//优惠券自动过期
			result = couponUserMapper.updateExpireCouponStatus();
			//红包自动过期
			result = redpackageUserMapper.updateExpireRedPackageStatus();
			transactionManager.commit(status);
		} catch (Exception e) {
			transactionManager.rollback(status);
			logger.error("已发红包与优惠券自动过期commit", e);
			throw e;
		}

		return result;
	}

	//动态活动到期自动结束
	private int autoExpireForUnroutineActivity()throws Exception{
		int result =0;

		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务
		TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态

		try {
			//动态活动到期自动结束
			activityUnroutineService.endAllExpireUnroutineActivity();
			transactionManager.commit(status);
		} catch (Exception e) {
			transactionManager.rollback(status);
			logger.error("动态活动到期自动结束commit", e);
			throw e;
		}

		return result;
	}

	//服务商品过期自动下架
	private int autoOfflineExpireServiceGood()throws Exception{
		int result =0;

		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); // 事物隔离级别，开启新事务
		TransactionStatus status = transactionManager.getTransaction(def); // 获得事务状态

		try {
			//动态活动到期自动结束
			result = mallGoodMapper.updateExpireGood();
			transactionManager.commit(status);
		} catch (Exception e) {
			transactionManager.rollback(status);
			logger.error("动态活动到期自动结束commit", e);
			throw e;
		}

		return result;
	}

	private int saveAutoAddAmount() throws Exception{
		//红包自动增加金额
		List<Redpackage> redpackagesList = redpackageMapper.selectAutoAddAmountList(Const.REDPACKAGE_FREEZE_AMOUNT_MIN);
		for (Redpackage redpackage:redpackagesList) {
			//计算需要增加的金额
			redpackage.setSumAmount(redpackage.getSumAmount()==null?0:redpackage.getSumAmount());
			redpackage.setUsedAmount(redpackage.getUsedAmount()==null?0:redpackage.getUsedAmount());
			Integer addAmount = Const.REDPACKAGE_FREEZE_AMOUNT - (redpackage.getSumAmount() - redpackage.getUsedAmount());
			if(addAmount<=0)
				continue;

			Redpackage record = new Redpackage();
			record.setId(redpackage.getId());
			record.setGmtModified(new Date());
			record.setSumAmount(redpackage.getSumAmount() + addAmount);
			redpackageMapper.updateByPrimaryKeySelective(record);

			//增加营销账户冻结金额
			groupAccountService.updateAmount(redpackage.getGroupId(),BizEnum.SaleAccountSubjectType.RedPackageCreate,addAmount,record.getId(),null,null);
		}

		//优惠券自动增加金额
		List<Coupon> couponList = couponMapper.selectAutoAddAmountList(Const.COUPON_FREEZE_AMOUNT_MIN);
		for (Coupon coupon:couponList) {
			//计算需要增加的金额
			coupon.setSumAmount(coupon.getSumAmount()==null?0:coupon.getSumAmount());
			coupon.setVerifiedCount(coupon.getVerifiedCount()==null?0:coupon.getVerifiedCount());

			Integer addAmount = Const.COUPON_FREEZE_AMOUNT - (coupon.getSumAmount() - coupon.getVerifiedCount()*coupon.getSettedValue());
			if(addAmount<=0)
				continue;

			Coupon record = new Coupon();
			record.setId(coupon.getId());
			record.setGmtModified(new Date());
			record.setSumAmount(coupon.getSumAmount() + addAmount);
			couponMapper.updateByPrimaryKeySelective(record);

			//增加营销账户冻结金额
			groupAccountService.updateAmount(coupon.getGroupId(),BizEnum.SaleAccountSubjectType.CouponCreate,addAmount,record.getId(),null,null);
		}
        return 1;
	}

	//固定活动生日任务
	private int saveActivityRoutineBirthDayTask(Date statisDate) throws Exception {
		int result = 0;

		int count =0;

		//生日送
		List<ActivityRoutine> activityRoutineList = activityRoutineMapper.selectByActivityType(ActivityEnum.RoutineActivityType.BirthDaySend.getType());
		for(ActivityRoutine activityRoutine:activityRoutineList) {
			ActivityBase activityBase = activityBaseMapper.selectByRoutineId(activityRoutine.getActivityId());

			//全部会员或等级会员一同处理
			//if(activityRoutine.getMemberRiented() == ActivityEnum.MemberOriented.AllMember.getType()){
			List<ActivityRoutineRule> activityRoutineRuleList = activityRoutineRuleMapper.selectValidRuleListByActivityId(activityRoutine.getActivityId());
			for (ActivityRoutineRule activityRoutineRule : activityRoutineRuleList) {
				List<Member> memberIdList = memberMapper.getMemberByCondition(activityBase.getGroupId(), activityRoutineRule.getMemberGrade(),
						DateUtil.getAfterDay(statisDate,  activityRoutine.getSendTime()), null);
				for (Member member : memberIdList) {
					if(activityRoutineRule.getSendType()==null)
						activityRoutineRule.setSendType(ActivityEnum.ActivitySendType.NoSend.getType());
					switch (ActivityEnum.ActivitySendType.fromType(activityRoutineRule.getSendType())) {
						case RedPackage:
							try {
								count = redpackageUserMapper.selectThisYearSendRedpackageCount(member.getId(),activityBase.getId());
								if(count > 0){
									logger.info("会员:" + member.getId() + "本年度生日已送红包！");
								}else {
									result = redPackageUserService.sendOneMemberRedPackage(member.getId(),
											activityRoutineRule.getRedpackageId(), activityBase.getId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), null);
								}
							}catch (Exception ae){
								logger.error(ae);
							}
							break;
						case Coupon:
							try {
								count = couponUserMapper.selectThisYearSendCouponCount(member.getId(),activityBase.getId());
								if(count > 0){
									logger.info("会员:" + member.getId() + "本年度生日已送优惠券！");
								}else {
									result = couponUserService.sendOneMemberCoupon(member.getId(),
											activityRoutineRule.getCouponId(), activityBase.getId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), null);
								}
							}catch (Exception ae){
								logger.error(ae);
							}
							break;
						case Bonus:
							try {
								BonusSendLog bonusSendLog = BonusSendLog.build(activityBase.getGroupId(),member.getId(), ActivityEnum.BonusSendType.routineActivityBirthday.getType(),
										activityRoutineRule.getIntegral(), ActivityEnum.BonusSendStatus.Accounted.getType(),null,null,null,"固定活动生日送",activityBase.getId());
								result = bonusService.sendOneMemberBonus(bonusSendLog);
							} catch (Exception e) {
								e.printStackTrace();
								logger.error(e);
							}
							break;
					}
				}
			}
			//}
		}
		return result;
	}

	//固定活动固定时间任务
	private int saveActivityRoutineFixedTimeTask(Date statisDate) throws Exception{
		int result = 0;
		StringBuffer sb = new StringBuffer();
		//固定时间送
		List<ActivityRoutine> activityRoutineList = activityRoutineMapper.selectByActivityType(ActivityEnum.RoutineActivityType.FixedTime.getType());
		for(ActivityRoutine activityRoutine:activityRoutineList) {
			if(activityRoutine.getFixedDate() == null ){
				logger.info(sb.append("固定时间未设指！"));
				continue;
			}
			activityRoutine.setSendTime(activityRoutine.getSendTime()==null?0:activityRoutine.getSendTime());
			if (statisDate.compareTo(DateUtil.getAfterDay(activityRoutine.getFixedDate(), -1 * (activityRoutine.getSendTime()))) != 0) {
				logger.info(sb.append("固定时间活动(ID号:").append(activityRoutine.getActivityId()).append(")未到指定日期"));
				continue;
			}
			ActivityBase activityBase = activityBaseMapper.selectByRoutineId(activityRoutine.getActivityId());

			//全部会员或等级会员一同处理
			//if(activityRoutine.getMemberRiented() == ActivityEnum.MemberOriented.AllMember.getType()){
			List<ActivityRoutineRule> activityRoutineRuleList = activityRoutineRuleMapper.selectValidRuleListByActivityId(activityRoutine.getActivityId());
			for (ActivityRoutineRule activityRoutineRule : activityRoutineRuleList) {
				List<Member> memberIdList = memberMapper.getMemberByCondition(activityBase.getGroupId(), activityRoutineRule.getMemberGrade(), null, null);
				for (Member member : memberIdList) {
					if(activityRoutineRule.getSendType()==null)
						activityRoutineRule.setSendType(ActivityEnum.ActivitySendType.NoSend.getType());
					switch (ActivityEnum.ActivitySendType.fromType(activityRoutineRule.getSendType())) {
						case RedPackage:
							try {
								result = redPackageUserService.sendOneMemberRedPackage(member.getId(),
										activityRoutineRule.getRedpackageId(), activityBase.getId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), null);
							}catch (Exception ae){
								logger.error(ae);
							}
							break;
						case Coupon:
							try{
								result = couponUserService.sendOneMemberCoupon(member.getId(),
								 	activityRoutineRule.getCouponId(), activityBase.getId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), null);
							}catch (Exception ae){
								logger.error(ae);
							}
							break;
						case Bonus:
							try {
								BonusSendLog bonusSendLog = BonusSendLog.build(activityBase.getGroupId(),member.getId(), ActivityEnum.BonusSendType.routineActivityTime.getType(),
										activityRoutineRule.getIntegral(), ActivityEnum.BonusSendStatus.Accounted.getType(),null,null,null,"固定活动固定时间送",activityBase.getId());
								result = bonusService.sendOneMemberBonus(bonusSendLog);
							} catch (Exception e) {
								e.printStackTrace();
								logger.error(e);
							}
							break;

					}
				}
			}
			//}
		}
		return result;
	}

	//固定活动升级送任务
	public int saveActivityRoutineUpdateSendTask(Date statisDate) throws Exception{
		int result=0;
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("taskType", TaskType.ActivityRoutineUpdateDayTask.getType());
		param.put("taskDate", statisDate);

		SysTaskLog oldRecord = sysTaskLogMapper.selectSysTaskLogByTypeAndDate(param);
		if(oldRecord  != null && oldRecord.getResultStatus() == RunStatus.Success.getType()){
			throw new ApplicationException(Rescode.FAIL,"计划任务已经执行成功！");
		}

		StringBuffer sb = new StringBuffer();
		//
		List<ActivityRoutine> activityRoutineList = activityRoutineMapper.selectByActivityType(ActivityEnum.RoutineActivityType.UpdateSend.getType());
		for(ActivityRoutine activityRoutine:activityRoutineList) {
			ActivityBase activityBase = activityBaseMapper.selectByRoutineId(activityRoutine.getActivityId());

			//全部会员或等级会员一同处理
			//if(activityRoutine.getMemberRiented() == ActivityEnum.MemberOriented.AllMember.getType()){
			List<ActivityRoutineRule> activityRoutineRuleList = activityRoutineRuleMapper.selectValidRuleListByActivityId(activityRoutine.getActivityId());
			for (ActivityRoutineRule activityRoutineRule : activityRoutineRuleList) {
				List<Member> memberIdList = memberMapper.getMemberByCondition(activityBase.getGroupId()
						, activityRoutineRule.getMemberGrade(), null, DateUtil.getAfterDay(statisDate, -1 * activityRoutine.getSendTime()));
				for (Member member : memberIdList) {
					if(activityRoutineRule.getSendType()==null)
						activityRoutineRule.setSendType(ActivityEnum.ActivitySendType.NoSend.getType());
					switch (ActivityEnum.ActivitySendType.fromType(activityRoutineRule.getSendType())) {
						case RedPackage:
							try {
								result = redPackageUserService.sendOneMemberRedPackage(member.getId(),
										activityRoutineRule.getRedpackageId(), activityBase.getId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), null);
							}catch (Exception ae){
								ae.printStackTrace();
								logger.error(ae);
							}
							break;
						case Coupon:
							try {
								result = couponUserService.sendOneMemberCoupon(member.getId(),
										activityRoutineRule.getCouponId(), activityBase.getId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(), null);
							}catch (Exception ae){
								ae.printStackTrace();
								logger.error(ae);
							}
							break;
						case Bonus:
							try {
								BonusSendLog bonusSendLog = BonusSendLog.build(activityBase.getGroupId(),member.getId(), ActivityEnum.BonusSendType.UpdateSend.getType(),
										activityRoutineRule.getIntegral(), ActivityEnum.BonusSendStatus.Accounted.getType(),null,null,null,"会员升级送",activityBase.getId());
								result = bonusService.sendOneMemberBonus(bonusSendLog);
							} catch (Exception e) {
								e.printStackTrace();
								logger.error(e);
							}
							break;
						default:
							break;
					}
				}
			}
			//}
		}

		//插入计划任务成功日志
		if(oldRecord  == null){
			SysTaskLog record = new SysTaskLog();
			record.setGmtCreate(new Date());
			record.setGmtModified(new Date());
			record.setTaskType(TaskType.ActivityRoutineUpdateDayTask.getType());
			record.setTaskDate(statisDate);
			record.setResultStatus(RunStatus.Success.getType());
			record.setRunTimes(0);
			record.setMemo(sb.toString());
			result = sysTaskLogMapper.insert(record);
		}
		else{
			oldRecord.setGmtModified(new Date());
			oldRecord.setResultStatus(RunStatus.Success.getType());
			oldRecord.setRunTimes((oldRecord.getRunTimes()==null?0:oldRecord.getRunTimes())+1);
			oldRecord.setMemo(sb.toString());
			result = sysTaskLogMapper.updateByPrimaryKeySelective(oldRecord);
		}

		return result;
	}

	//固定活动会员生命周期任务
	private int saveActivityMemberLifeCycleSendTask(Date statisDate) throws Exception{
		int result = 0;
		StringBuffer sb = new StringBuffer();
		String memo = "";
        int count = 0;

		//会员生命周期送
		List<ActivityRoutine> activityRoutineList = activityRoutineMapper.selectByActivityType(ActivityEnum.RoutineActivityType.MemberLifeCycle.getType());
		for(ActivityRoutine activityRoutine:activityRoutineList) {
			ActivityBase activityBase = activityBaseMapper.selectByRoutineId(activityRoutine.getActivityId());

			//全部会员或等级会员一同处理
			//if(activityRoutine.getMemberRiented() == ActivityEnum.MemberOriented.AllMember.getType()){
			List<ActivityRoutineRule> activityRoutineRuleList = activityRoutineRuleMapper.selectValidRuleListByActivityId(activityRoutine.getActivityId());
			for (ActivityRoutineRule activityRoutineRule : activityRoutineRuleList) {
				List<Member> memberIdList = null;
				activityRoutineRule.setUndoDays(activityRoutineRule.getUndoDays() == null ? 0 : activityRoutineRule.getUndoDays());
				if (ActivityEnum.LifecycleType.fromType(activityRoutineRule.getLifecycleType()) == ActivityEnum.LifecycleType.Login) {
					memberIdList = memberMapper.getMemberByUnLogin(activityBase.getGroupId(), activityRoutineRule.getMemberGrade(),
							DateUtil.getAfterDay(statisDate, -1 * activityRoutineRule.getUndoDays()));
					memo = "会员生命周期送:" +  ActivityEnum.LifecycleType.Login.getName();
				}
				if (ActivityEnum.LifecycleType.fromType(activityRoutineRule.getLifecycleType()) == ActivityEnum.LifecycleType.Consume) {
					memberIdList = memberMapper.getMemberByUnTrade(activityBase.getGroupId(), activityRoutineRule.getMemberGrade(),
							DateUtil.getAfterDay(statisDate, -1 * activityRoutineRule.getUndoDays()));
					memo = "会员生命周期送:" +  ActivityEnum.LifecycleType.Consume.getName();
				}
				for (Member member : memberIdList) {
					if(activityRoutineRule.getSendType()==null)
						activityRoutineRule.setSendType(ActivityEnum.ActivitySendType.NoSend.getType());

					switch (ActivityEnum.ActivitySendType.fromType(activityRoutineRule.getSendType())) {
						case RedPackage:
							try {
								//暂时不加已发放控制，由优惠券属性控制
                                /*count = redpackageUserMapper.selectSendedActivityRedpackageCount(member.getId(),activityBase.getId(),activityRoutineRule.getRedpackageId());
                                if(count>0){
                                	continue;
                                }*/
								result = redPackageUserService.sendOneMemberRedPackage(member.getId(),
										activityRoutineRule.getRedpackageId(), activityBase.getId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(),memo, null);
							}catch (Exception ae){
								logger.error(ae);
							}
							break;
						case Coupon:
							try {
								result = couponUserService.sendOneMemberCoupon(member.getId(),
										activityRoutineRule.getCouponId(), activityBase.getId(), ActivityEnum.RedPackageGetType.ActivitySend.getType(),memo, null);
							}catch (Exception ae){
								logger.error(ae);
							}
							break;
						case Bonus:
							try {
								BonusSendLog bonusSendLog = BonusSendLog.build(activityBase.getGroupId(),member.getId(), ActivityEnum.BonusSendType.routineActivityCycleLife.getType(),
										activityRoutineRule.getIntegral(), ActivityEnum.BonusSendStatus.Accounted.getType(),null,null,null,"固定活动周期送",activityBase.getId());
								result = bonusService.sendOneMemberBonus(bonusSendLog);
							} catch (Exception e) {
								e.printStackTrace();
								logger.error(e);
							}
							break;
					}
				}
			}
			//}
		}
		return result;
	}

	public int saveActivityMonthTask(Date statisDate) throws Exception{
		int result=0;
		Map<String,Object> param=new HashMap<String,Object>();
		param.put("taskType", TaskType.ActivityMonthTask.getType());
		param.put("taskDate", statisDate);

		SysTaskLog oldRecord = sysTaskLogMapper.selectSysTaskLogByTypeAndDate(param);
		if(oldRecord  != null && oldRecord.getResultStatus() == RunStatus.Success.getType()){
			throw new ApplicationException(Rescode.FAIL,"计划任务已经执行成功！");
		}
		StringBuffer sb = new StringBuffer();
		//固定活动邀请注册赠送月任务
		saveActivityInviteRegistrationSendTask(statisDate);

		//插入计划任务成功日志
		if(oldRecord  == null){
			SysTaskLog record = new SysTaskLog();
			record.setGmtCreate(new Date());
			record.setGmtModified(new Date());
			record.setTaskType(TaskType.ActivityMonthTask.getType());
			record.setTaskDate(statisDate);
			record.setResultStatus(RunStatus.Success.getType());
			record.setRunTimes(0);
			record.setMemo(sb.toString());
			result = sysTaskLogMapper.insert(record);
		}
		else{
			oldRecord.setGmtModified(new Date());
			oldRecord.setResultStatus(RunStatus.Success.getType());
			oldRecord.setRunTimes((oldRecord.getRunTimes()==null?0:oldRecord.getRunTimes())+1);
			oldRecord.setMemo(sb.toString());
			result = sysTaskLogMapper.updateByPrimaryKeySelective(oldRecord);
		}

		return result;
	}

	//固定活动邀请注册赠送月任务
	private int saveActivityInviteRegistrationSendTask(Date statisDate) throws Exception{
		int result = 0;
		StringBuffer sb = new StringBuffer();

		List<ActivityRoutineRegister> activityRoutineRegisters = activityRoutineRegisterMapper.selectByActivityType(ActivityEnum.RoutineActivityType.InviteRegistration.getType());
		for(ActivityRoutineRegister activityRoutineRegister:activityRoutineRegisters) {
			ActivityBase activityBase = activityBaseMapper.selectByRoutineId(activityRoutineRegister.getActivityId());

			if (activityRoutineRegister.getManyIsOpen()==null || (!activityRoutineRegister.getManyIsOpen())) {
				logger.info(sb.append("固定时间活动(ID号:").append(activityRoutineRegister.getActivityId()).append(")多邀请多奖励未开启!"));
				continue;
			}

			List<StatisMemberMonth> memberMonthList = null;
			//处理一级邀请会员
			memberMonthList = statisMemberMonthMapper.getMemberByInviteNumber(activityBase.getGroupId(),
					activityRoutineRegister.getFirstPeopleNum(), activityRoutineRegister.getSecondPeopleNum(), statisDate);
			for (StatisMemberMonth memberMonth : memberMonthList) {
				if(activityRoutineRegister.getFirstSendType()==null)
					activityRoutineRegister.setFirstSendType(ActivityEnum.ActivitySendType.NoSend.getType());

				switch (ActivityEnum.ActivitySendType.fromType(activityRoutineRegister.getFirstSendType())) {
					case RedPackage:
						try {
							result = redPackageUserService.sendOneMemberRedPackage(memberMonth.getMemberId(),
									activityRoutineRegister.getFirstRedpackageId(), activityBase.getId(),
									ActivityEnum.RedPackageGetType.ActivitySend.getType(), "月邀请" + activityRoutineRegister.getFirstPeopleNum() + "人赠送", null);
						}catch (Exception ae){
							logger.error(ae);
						}
						break;
					case Coupon:
						try {
							result = couponUserService.sendOneMemberCoupon(memberMonth.getMemberId(),
									activityRoutineRegister.getFirstCouponId(), activityBase.getId(),
									ActivityEnum.RedPackageGetType.ActivitySend.getType(), "月邀请" + activityRoutineRegister.getFirstPeopleNum() + "人赠送", null);
						}catch (Exception ae){
							logger.error(ae);
						}

						break;
					case Bonus:
						try {
							BonusSendLog bonusSendLog = BonusSendLog.build(activityBase.getGroupId(),memberMonth.getMemberId(), ActivityEnum.BonusSendType.routineActivityRegister.getType(),
									Integer.parseInt(String.valueOf(activityRoutineRegister.getFirstIntegral())), ActivityEnum.BonusSendStatus.Accounted.getType(),null,null,null,"固定活动邀请注册送",activityBase.getId());
							result = bonusService.sendOneMemberBonus(bonusSendLog);
						} catch (Exception e) {
							e.printStackTrace();
							logger.error(e);
						}
						break;
				}
			}
			//处理二级邀请会员
			memberMonthList = statisMemberMonthMapper.getMemberByInviteNumber(activityBase.getGroupId(),
					activityRoutineRegister.getSecondPeopleNum(), activityRoutineRegister.getThirdPeopleNum(), statisDate);
			for (StatisMemberMonth memberMonth : memberMonthList) {
				if(activityRoutineRegister.getSecondSendType()==null)
					activityRoutineRegister.setSecondSendType(ActivityEnum.ActivitySendType.NoSend.getType());

				switch (ActivityEnum.ActivitySendType.fromType(activityRoutineRegister.getSecondSendType())) {
					case RedPackage:
						try {
							result = redPackageUserService.sendOneMemberRedPackage(memberMonth.getMemberId(),
									activityRoutineRegister.getSecondRedpackageId(), activityBase.getId(),
									ActivityEnum.RedPackageGetType.ActivitySend.getType(), "月邀请" + activityRoutineRegister.getSecondPeopleNum() + "人赠送", null);
						}catch (Exception ae){
							logger.error(ae);
						}
						break;
					case Coupon:
						try {
							result = couponUserService.sendOneMemberCoupon(memberMonth.getMemberId(),
									activityRoutineRegister.getSecondCouponId(), activityBase.getId(),
									ActivityEnum.RedPackageGetType.ActivitySend.getType(), "月邀请" + activityRoutineRegister.getSecondPeopleNum() + "人赠送", null);
						}catch (Exception ae){
							logger.error(ae);
						}
						break;
					case Bonus:
						try {
							BonusSendLog bonusSendLog = BonusSendLog.build(activityBase.getGroupId(),memberMonth.getMemberId(), ActivityEnum.BonusSendType.routineActivityRegister.getType(),
									Integer.parseInt(String.valueOf(activityRoutineRegister.getSecondIntegral())), ActivityEnum.BonusSendStatus.Accounted.getType(),null,null,null,"固定活动邀请注册送",activityBase.getId());
							result = bonusService.sendOneMemberBonus(bonusSendLog);
						} catch (Exception e) {
							e.printStackTrace();
							logger.error(e);
						}
						break;
				}
			}
			//处理三级邀请会员
			memberMonthList = statisMemberMonthMapper.getMemberByInviteNumber(activityBase.getGroupId(),
					activityRoutineRegister.getThirdPeopleNum(), null, statisDate);
			for (StatisMemberMonth memberMonth : memberMonthList) {
				if(activityRoutineRegister.getThirdSendType()==null)
					activityRoutineRegister.setThirdSendType(ActivityEnum.ActivitySendType.NoSend.getType());

				switch (ActivityEnum.ActivitySendType.fromType(activityRoutineRegister.getThirdSendType())) {
					case RedPackage:
						try {
							result = redPackageUserService.sendOneMemberRedPackage(memberMonth.getMemberId(),
									activityRoutineRegister.getThirdRedpackageId(), activityBase.getId(),
									ActivityEnum.RedPackageGetType.ActivitySend.getType(), "月邀请" + activityRoutineRegister.getThirdPeopleNum() + "人赠送", null);
						}catch (Exception ae){
							logger.error(ae);
						}
						break;
					case Coupon:
						try {
							result = couponUserService.sendOneMemberCoupon(memberMonth.getMemberId(),
									activityRoutineRegister.getThirdCouponId(), activityBase.getId(),
									ActivityEnum.RedPackageGetType.ActivitySend.getType(), "月邀请" + activityRoutineRegister.getThirdPeopleNum() + "人赠送", null);
						}catch (Exception ae){
							logger.error(ae);
						}
						break;
					case Bonus:
						try {
							BonusSendLog bonusSendLog = BonusSendLog.build(activityBase.getGroupId(),memberMonth.getMemberId(), ActivityEnum.BonusSendType.routineActivityRegister.getType(),
									Integer.parseInt(String.valueOf(activityRoutineRegister.getThirdIntegral())), ActivityEnum.BonusSendStatus.Accounted.getType(),null,null,null,"固定活动邀请注册送",activityBase.getId());
							result = bonusService.sendOneMemberBonus(bonusSendLog);
						} catch (Exception e) {
							e.printStackTrace();
							logger.error(e);
						}
						break;
				}
			}
		}
		return result;
	}
}
